package com.zr.task.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jietong.rfid.util.EPC;
import com.zh.baselibrary.base.BaseNoIMActivity;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.netutils.NetUtil;
import com.zh.baselibrary.utils.ClickUtils;
import com.zh.baselibrary.utils.ComparatorUtils;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.JsonUtils;
import com.zh.baselibrary.utils.ListUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.task.SubjectBean;
import com.zh.model.task.home.CabinetBean;
import com.zh.model.task.home.ClassCabinetBean;
import com.zh.model.task.home.RemoteOpenResVO;
import com.zh.model.task.subject.LoginResBean;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.task.R;
import com.zr.task.TaskApplication;
import com.zr.task.adapter.HomeCabinetAdapter;
import com.zr.task.constant.Constant;
import com.zr.task.dialog.ManagerVerificationDialog;
import com.zr.task.presenter.TaskMainPresenter;
import com.zr.task.presenter.view.TaskMainView;
import com.zr.task.utils.EquipmentTypeUtils;
import com.zr.task.view.SubjectView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;


public class TaskMainActivity extends BaseNoIMActivity<TaskMainPresenter> implements View.OnClickListener, SubjectView.ToOpen, TaskMainView {

    @BindView(R.id.stub_home)
    ViewStub viewStubHome;
    @BindView(R.id.stub_subject)
    ViewStub viewStubSubject;
    @BindView(R.id.iv_logo)
    ImageView imageViewLogo;
    @BindView(R.id.iv_back)
    ImageView imageViewBack;

    /**
     * 空闲时间
     */
    private static final Long MILLISINFUTURE = (long) 61 * 1000;
    /**
     * 倒计时间隔
     */
    private static final Long COUNTDOWNINTERVAL = (long) 1 * 1000;
    private RecyclerView mRyCabinet;
    private TextView mTvLocation;
    private LinearLayout subjectLayout;

    private HomeCabinetAdapter mAdapter;
    private Integer clickType = 0;
    private CountDownTimer countTimer;

    private ManagerVerificationDialog mVerificationDialog;
    private boolean isStop = false;
    View homeView, subjectView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_main;
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        initHome();
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Constant.BROAT_CAST_ACTION_HOME_FRESH);
        mIntentFilter.addAction(Constant.BROAT_CAST_ACTION_ERROR_COMPLTE);
        mIntentFilter.addAction(BaseConstant.BROAT_CAST_ACTION_EQUIPMENT_UPDATE);
        registerReceiver(broadcastReceiver, mIntentFilter);
        mPresenter.getCabinetDetail();
        findViewById(R.id.iv_logo).setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.tv_about).setOnClickListener(this);
        mPresenter.initDevice();
        TTSUtils.getInstance().init(TaskApplication.getContext());
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 8, AudioManager.FLAG_PLAY_SOUND);
    }

    @Override
    protected TaskMainPresenter createPresenter() {

        return new TaskMainPresenter(ShareManager.getValue(this, BaseConstant.DEVICE_SCHOOL_ID), PhoneUtil.getUUID(this));
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(Constant.BROAT_CAST_ACTION_HOME_FRESH)) {
                mPresenter.getCabinetDetail();
//                ClassCabinetBean mBean = JsonUtils.stringToObject(ShareManager.getValue(TaskMainActivity.this, BaseConstant.LOCAL_CAB_LIST), ClassCabinetBean.class);
//                upViewHome(mBean);

            } else if (intent.getAction().equals(Constant.BROAT_CAST_ACTION_ERROR_COMPLTE)) {
                mPresenter.errorComplete(intent);

            } else if (intent.getAction().equals(BaseConstant.BROAT_CAST_ACTION_EQUIPMENT_UPDATE)) {
                ClassCabinetBean mBean = JsonUtils.stringToObject(ShareManager.getValue(TaskMainActivity.this, BaseConstant.LOCAL_CAB_LIST), ClassCabinetBean.class);
                upViewHome(mBean);
            }
        }
    };

    private void initHome() {
        imageViewLogo.setVisibility(View.VISIBLE);
        imageViewBack.setVisibility(View.INVISIBLE);
        if (homeView == null) {
            homeView = viewStubHome.inflate();
            mTvLocation = homeView.findViewById(R.id.tv_location);
            mRyCabinet = homeView.findViewById(R.id.ry_cabinet);
            homeView.findViewById(R.id.tv_subject).setOnClickListener(this);
            homeView.findViewById(R.id.tv_error).setOnClickListener(this);
            homeView.findViewById(R.id.tv_relation).setOnClickListener(this);
            if (!EquipmentTypeUtils.hasRf(this)) {
                homeView.findViewById(R.id.tv_error).setVisibility(View.GONE);
                homeView.findViewById(R.id.tv_relation).setVisibility(View.GONE);
            }
            mAdapter = new HomeCabinetAdapter(new ArrayList<>());
            mRyCabinet.setAdapter(mAdapter);
        } else {
            viewStubHome.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        NetUtil.getNetType(this);
        isStop = false;
        mPresenter.beginInvV2();
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStop = true;
        if(mPresenter!=null)
        mPresenter.stopInvV2();
    }

    @Override
    public void initSubject(LoginResBean loginResBean) {
        mPresenter.stopInvV2();
        countTimer = new CountDownTimer(MILLISINFUTURE, COUNTDOWNINTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                hideSubject();
            }
        };
        countTimer.start();
        viewStubHome.setVisibility(View.GONE);
        imageViewBack.setVisibility(View.VISIBLE);
        imageViewLogo.setVisibility(View.INVISIBLE);
        if (subjectView == null) {
            subjectView = viewStubSubject.inflate();
            subjectLayout = subjectView.findViewById(R.id.linearLayout_contain);
            subjectLayout.removeAllViewsInLayout();
            for (SubjectBean subjectBean : loginResBean.getCabinetDetailVOList()) {
                SubjectView view = new SubjectView(this, subjectBean, loginResBean.getName(), this);
                view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                subjectLayout.addView(view);
            }
        } else {
            viewStubSubject.setVisibility(View.VISIBLE);
            subjectLayout.removeAllViewsInLayout();
            for (SubjectBean subjectBean : loginResBean.getCabinetDetailVOList()) {
                SubjectView view = new SubjectView(this, subjectBean, loginResBean.getName(), this);
                view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                subjectLayout.addView(view);
            }
        }
    }

    public void hideSubject() {
        mPresenter.beginInvV2();
        mPresenter.setClickedSub(false);
        if(countTimer!=null) {
            countTimer.cancel();
            countTimer = null;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                viewStubSubject.setVisibility(View.GONE);
                initHome();
            }
        });

    }

    @Override
    public void initMore() {
        if (!EquipmentTypeUtils.hasRf(this)) {
            if(homeView!=null) {
                homeView.findViewById(R.id.tv_error).setVisibility(View.GONE);
                homeView.findViewById(R.id.tv_relation).setVisibility(View.GONE);
            }
        }else {
            if(homeView!=null) {
                homeView.findViewById(R.id.tv_error).setVisibility(View.VISIBLE);
                homeView.findViewById(R.id.tv_relation).setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public int getClickType() {
        return clickType;
    }

    @Override
    public void setClickType(int type) {
        clickType = type;
    }

    //关门
    @Override
    public void doorClose(String tip) {
        clickType =0;
        mPresenter.beginInvV2();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastView.showLong(tip);
            }
        });

    }


    @Override
    public void upViewHome(ClassCabinetBean cabinetBean) {
        if (cabinetBean == null)
            cabinetBean = new ClassCabinetBean();
        mTvLocation.setText(cabinetBean.getLocation());
        int count = EquipmentTypeUtils.getBoxNum(this);
        int span = (count + 1) / 3;
        if (span == 0)
            span = 1;
        mRyCabinet.setLayoutManager(new GridLayoutManager(this, span));
        int host = 0;
        if (count > 2)
            host = 1;
        if (!ListUtils.isEmpty(cabinetBean.getCabinetDetailList())) {
            Collections.sort(cabinetBean.getCabinetDetailList(), new ComparatorUtils("", "cabinetNum", true));
            int first = cabinetBean.getCabinetDetailList().get(0).getCabinetNum();  //第一个柜子不为1，加null
            int cha = first -1;
            for (int k = 0; k < cha; k++) {
                cabinetBean.getCabinetDetailList().add(0,null);
            }
            cabinetBean.getCabinetDetailList().add(host, null);
        }
        mAdapter.setCount(count + 1); //设置adapter数量
        mAdapter.clearAdd(compliteData(host,cabinetBean.getCabinetDetailList()));
    }
    //补全null
    public List<CabinetBean> compliteData(int host ,List<CabinetBean> list) {
        if (ListUtils.isEmpty(list))
            return list;
        List<CabinetBean> item = new ArrayList<>();
        LogUtils.e(JsonUtils.objectToString(list));
        int j = 1;
        int length = list.size();
        for (int i = 0; i < length; i++) {
            if (list.get(i) == null) {
                item.add(null);
                if(i!=host) {  //null可能为柜子，第一个柜子不为1(null null 2)
                    j++;
                }
            } else {
                if (list.get(i).getCabinetNum() == j) { //柜号没错
                    item.add(list.get(i));
                    j++;
                } else if (list.get(i).getCabinetNum() > j) { //相差，补null (124补一个3)
                    int cha = list.get(i).getCabinetNum() - j;
                    for (int k = 0; k < cha; k++) {
                        item.add(null);
                        j++;
                    }
                    i--;
                }
            }
        }
        return item;
    }
    @Override
    public HomeCabinetAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void onHint(String hint) {
        ToastView.showLong(hint);
        dismissDialog();
        mPresenter.beginInvV2();
        if(clickType ==1||clickType==2)
            TTSUtils.getInstance().speak(getString(R.string.identification_error));
        else if(clickType ==3)
            TTSUtils.getInstance().speak(getString(R.string.identification_error_more));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_logo) {
            threeClick();
            return;
        }
        if (ClickUtils.isFastClick()) {
            switch (v.getId()) {
                case R.id.tv_subject:
                    if (mRyCabinet.getVisibility() == View.INVISIBLE) {
                        ToastView.showLong("目前尚未分配科目");
                        return;
                    }
                    clickType = 1;
                    showDialog();
                    break;
                case R.id.tv_error:
                    if (BaseConstant.hasNet) {
                        if (mRyCabinet.getVisibility() == View.INVISIBLE) {
                            ToastView.showLong("目前尚未分配科目");
                            return;
                        }
                        clickType = 2;
                        showDialog();
                    } else {
                        EventBus.getDefault().post(274);
                        ToastView.showLong("网络异常，请稍后重试");
                    }
                    break;
                case R.id.tv_relation:
                    if (BaseConstant.hasNet) {
                        clickType = 3;
                        showDialog();
                    } else {
                        EventBus.getDefault().post(274);
                        ToastView.showLong("网络异常，请稍后重试");
                    }
                    break;
                case R.id.tv_about:
                    startActivity(new Intent(this, AboutActivity.class));
                    break;
                case R.id.iv_back:
                    if (mPresenter.isClickedSub())
                        ToastView.showShort("请先取出作业，关门");
                    else
                        hideSubject();
                    break;
            }
        }
    }

    private void showDialog() {
        mPresenter.stopInvV2();
        mVerificationDialog = new ManagerVerificationDialog(this, R.style.DialogTheme, new ManagerVerificationDialog.OnCloseListener() {
            @Override
            public void OnClose() {
                mPresenter.beginInvV2();
            }
        });
        mVerificationDialog.setShowQRCode(false);
        mVerificationDialog.show();
    }

    @Override
    public void dismissDialog() {
        if (mVerificationDialog != null) {
            mVerificationDialog.cancel();
        }
    }
    //硬件回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_VERIFICATION_SUCCSES) {  //磁卡登录
            String code = (String) hardEvent.getData();
            if (clickType == 1) {
                mPresenter.checkCard(code);
            } else if (clickType == 2) {
                mPresenter.errataSwipe(code);
            } else if (clickType == 3){
                mPresenter.swipingCard(code);
            }
        } else if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) { //门开启
            mPresenter.checkDoorClose((Integer) hardEvent.getData(),true);
        } else if (flag == AndeaConstant.CALL_LOCK_STATUS_ERROR || flag == AndeaConstant.CALL_READ_CHECK_CLOSE_ERROR || flag == AndeaConstant.CALL_INIT_CHECK_ERROR) {
            String tip = (String) hardEvent.getData();
            ToastView.showLong((String) hardEvent.getData());
            if (flag == AndeaConstant.CALL_LOCK_STATUS_ERROR) {
                mPresenter.openResult(0,1);
                if(tip.equals("柜门处于开启状态")) {
                    mPresenter.checkDoorClose(mPresenter.getOpenNum(), false);
                }else {
                    TTSUtils.getInstance().speak(getString(R.string.can_not_open));
                }
            }
        } else if (flag == AndeaConstant.CALL_READ_CHECK_SUCCSES) { // 盘点数据
            EPC epcTag = (EPC) hardEvent.getData();
            mPresenter.commit(epcTag);
        } else if (flag == AndeaConstant.CALL_REMOTE_OPEN) { //远程开启
            mPresenter.remoteOpen((RemoteOpenResVO) hardEvent.getData());
        } else if (flag == AndeaConstant.CALL_EMERGENCY) { //应急
            mPresenter.complete(true,(Integer) hardEvent.getData());
            if(!isStop)
            mPresenter.beginInvV2();
        }else if (flag == AndeaConstant.CALL_CORRIGEDUM) { //勘误
            if(!isStop)
                mPresenter.beginInvV2();
        }
    }

    //多课代表开门
    @Override
    public void toOpen(SubjectBean subjectBean, String name) {
        if (ClickUtils.isFastClick()) {
            clickType = 1;
            mPresenter.subClick(subjectBean, name);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //处理手势事件（根据个人需要去返回和逻辑的处理）
        switch (event.getAction()) {
            //获取触摸动作，如果ACTION_UP，计时开始。
            case MotionEvent.ACTION_UP:
                if (countTimer != null) {
                    countTimer.start();
                }
                break;
            //否则其他动作计时取消
            default:
                if (countTimer != null) {
                    countTimer.cancel();
                }
                break;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }

    int count;
    Long start, end;

    private void threeClick() {
        count++;
        if (count == 1)
            start = System.currentTimeMillis();
        if (count == 3)
            end = System.currentTimeMillis();
        if (count >= 3) {
            if ((end - start) < 700) {
                IntentUtils.instance().startActivity(this, AdminLoginActivity.class);
            }
            count = 0;
        }
        if ((System.currentTimeMillis() - start) > 1000) {
            count = 0;
            start = System.currentTimeMillis();
        }
    }
}
